package com.lumm.controller.api;

import com.alibaba.fastjson.JSONObject;
import com.lumm.model.*;
import com.lumm.services.DynamicService;
import com.lumm.services.RecommendService;
import com.lumm.services.UserService;
import com.lumm.util.EmailUtil;
import com.lumm.util.PasswordUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Controller
@RequestMapping("/api")

public class UserController {

    @Autowired

    private UserService userService;

    @Autowired

    private RecommendService recommendService;

    @Autowired
    private DynamicService dynamicService;


    @ResponseBody
    @RequestMapping("encryptPassword")
    public ResponseObject encryptPassword(@RequestParam(value = "password") String password) {
        return new ResponseObject(PasswordUtil.encryptPassword(password));
    }

    @ResponseBody
    @RequestMapping(value = "checkEmailAvailability", method = RequestMethod.GET)
    public ResponseObject checkEmailAvailability(@RequestParam(value = "email", required = true) String email) {
        return new ResponseObject(1, 1, userService.checkEmailAvailability(email));
    }

    //注册
    @ResponseBody
    @RequestMapping(value = "register", method = RequestMethod.GET)


    public ResponseObject register(
            @RequestParam(value = "email", required = false) String email,
            @RequestParam(value = "vcode", required = false) String vcode,
            @RequestParam(value = "password", required = false) String password,
            @RequestParam(value = "gender", required = false) String gender,
            @RequestParam(value = "birthday", required = false) String birthday,
            @RequestParam(value = "name", required = false) String name,
            @RequestParam(value = "phoneNum", required = false) String phoneNum,
            @RequestParam(value = "maritalStatus", required = false, defaultValue = "0") short maritalStatus,
            HttpSession session
    ) {
        //操作过程不合规范
        if (session.getAttribute("action") == null || !session.getAttribute("action").equals("register"))
            return new ResponseObject(0, -1);

        if (session.getAttribute("step").equals("1")) {
            //第一步
            String vcSave = (String) session.getAttribute("vcode");

            //验证码未设置
            if (vcSave == null || vcSave.equals(""))
                return new ResponseObject(0, 2);

            //验证码错误
            if (!vcSave.equals(vcode))
                return new ResponseObject(0, 3);

            //密码未设置
            if (password == null || password.equals(""))
                return new ResponseObject(0, 2);

            session.setAttribute("password", password);
            session.setAttribute("step", "2");

            return new ResponseObject(1, 1);
        } else {
            //第二步

            //未设置性别
            if (gender == null || gender.equals("") || (!gender.equals("男") && !gender.equals("女")))
                return new ResponseObject(0, 2);

            //未设置昵称
            if (name == null || name.equals(""))
                return new ResponseObject(0, 2);

            //未设置生日
            if (birthday == null || birthday.equals(""))
                return new ResponseObject(0, 2);

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

            Date birthdayDate;

            try {
                birthdayDate = sdf.parse(birthday);
            } catch (ParseException e) {
                e.printStackTrace();
                return new ResponseObject(0, 2);
            }


            //未设置手机号
            if (phoneNum == null || phoneNum.equals(""))
                return new ResponseObject(0, 2);

            //未设置婚姻状态
            if (maritalStatus < 1 || maritalStatus > 4)
                return new ResponseObject(0, 2);

            User user = userService.createNewUser((String) session.getAttribute("email"), (String) session.getAttribute("password"), gender, name, birthdayDate, phoneNum, maritalStatus);

            user.setPassword(null);

            session.setAttribute("login", "1");
            session.setAttribute("user", user);

            return new ResponseObject(1, 1, user);
        }
        //return new ResponseObject(0,2);
    }

    //登录
    @ResponseBody
    @RequestMapping(value = "login", method = RequestMethod.GET)

    public ResponseObject login(
            @RequestParam(value = "username", required = true) String username,
            @RequestParam(value = "password", required = true) String password,
            HttpSession session
    ) {

        int id = userService.login(username, password);

        if (id < 1000)
            return new ResponseObject(0, id);

        session.setAttribute("login", "1");

        User user = userService.querybyUserId(id);

        session.setAttribute("user", user);

        user.setPassword(null);

        return new ResponseObject(1, 0, user);
    }

    //获取验证码
    @ResponseBody
    @RequestMapping(value = "getEmailVcode", method = RequestMethod.GET)
    public ResponseObject getEmailVcode(
            @RequestParam(value = "email", required = true) String email,
            @RequestParam(value = "action", required = true) String action,
            HttpSession session
    ) {
        //邮箱格式不正确
        if (!EmailUtil.checkEmailFormat(email))
            return new ResponseObject(0, 2);

        if (action.equals("register")) {
            //邮箱已被占用
            if (!userService.checkEmailAvailability(email))
                return new ResponseObject(0, 3);
            session.setAttribute("action", "register");
            session.setAttribute("step", "1");
        } else {
            //邮箱未注册
            if (userService.checkEmailAvailability(email))
                return new ResponseObject(0, 5);
            session.setAttribute("action", "resetPassword");
        }
        session.setAttribute("vcode", userService.sendEmailVcode(email, action));
        session.setAttribute("email", email);
        return new ResponseObject(1, 1);
    }

    //获取用户信息
    @ResponseBody
    @RequestMapping(value = "getUserInfo", method = RequestMethod.GET)
    public ResponseObject getUserInfo(
            @RequestParam(value = "userId", required = false, defaultValue = "0") int userId,
            HttpSession session
    ) {
        if (userId == 0) {
            User user = (User) session.getAttribute("user");
            //用户未登录
            if (user == null || user.getUserId() == 0)
                return new ResponseObject(0, -1);
            return new ResponseObject(1, 1, user);
        } else {
            User user = userService.querybyUserId(userId);
            //用户不存在
            if (user == null || user.getUserId() == 0)
                return new ResponseObject(0, 5);
            return new ResponseObject(1, 1, user);
        }
    }

    //获取用户择偶意向
    @ResponseBody
    @RequestMapping(value = "getUserFavour", method = RequestMethod.GET)
    public ResponseObject getUserFavour(
            @RequestParam(value = "userId", required = false, defaultValue = "0") int userId,
            HttpSession session
    ) {
        if (userId == 0) {
            User user = (User) session.getAttribute("user");
            if (user == null || user.getUserId() == 0)
                return new ResponseObject(0, -1);
            return new ResponseObject(1, 1, userService.getUserDetails(user.getUserId()));
        } else {
            Favour favour = userService.getUserFavour(userId);
            //用户不存在
            if (favour == null || favour.getUserId() == 0)
                return new ResponseObject(0, 5);
            return new ResponseObject(1, 1, favour);
        }
    }

    //获取用户全部信息
    @ResponseBody
    @RequestMapping(value = "getUserAllInfo", method = RequestMethod.GET)
    public ResponseObject getUserAllInfo(
            @RequestParam(value = "userId", required = false, defaultValue = "0") int userId,
            HttpSession session
    ) {
        User user = (User) session.getAttribute("user");
        if (userId == 0) {

            if (user == null || user.getUserId() == 0)
                return new ResponseObject(0, -1);

            HashMap<String, Object> data = new HashMap<>();

            user.setPassword(null);

            data.put("info", user);
            data.put("details", userService.getUserDetails(user.getUserId()));

            return new ResponseObject(1, 1, data);
        } else {
            User otherOther = userService.querybyUserId(userId);
            //用户不存在
            if (otherOther == null || otherOther.getUserId() == 0)
                return new ResponseObject(0, 5);

            HashMap<String, Object> data = new HashMap<>();

            data.put("info", otherOther);
            data.put("details", userService.getUserDetails(otherOther.getUserId()));
            if (user != null)
                data.put("following", dynamicService.checkFollowing(user.getUserId(), userId));

            return new ResponseObject(1, 1, data);
        }
    }


    //获取用户详情
    @ResponseBody
    @RequestMapping(value = "getUserDetails", method = RequestMethod.GET)
    public ResponseObject getUserDetails(
            @RequestParam(value = "userId", required = false, defaultValue = "0") int userId,
            HttpSession session
    ) {

        if (userId == 0) {
            User user = (User) session.getAttribute("user");
            if (user == null || user.getUserId() == 0)
                return new ResponseObject(0, -1);
            return new ResponseObject(1, 1, userService.getUserDetails(user.getUserId()));
        } else {
            Details details = userService.getUserDetails(userId);
            //用户不存在
            if (details == null || details.getUserId() == 0)
                return new ResponseObject(0, 5);
            return new ResponseObject(1, 1, details);
        }
    }


    //获取推荐列表
    @ResponseBody
    @RequestMapping(value = "getRecommendList", method = RequestMethod.GET)
    public ResponseObject getRecommendList(
            HttpSession session
    ) {

        User user = (User) session.getAttribute("user");
        if (user == null || user.getUserId() == 0)
            return new ResponseObject(0, -1);
        return new ResponseObject(1, 1, recommendService.getRecommendList(user));
    }


    //重置密码
    @ResponseBody
    @RequestMapping(value = "resetPassword", method = RequestMethod.GET)
    public ResponseObject resultPassword(
            @RequestParam(value = "vcode", required = true) String vcode,
            @RequestParam(value = "password", required = true) String password,
            HttpSession session) {

        //操作过程不合规范
        if (session.getAttribute("action") == null || !session.getAttribute("action").equals("resetPassword"))
            return new ResponseObject(0, -1);

        String vcSave = (String) session.getAttribute("vcode");

        //验证码未设置
        if (vcSave == null || vcSave.equals(""))
            return new ResponseObject(0, -1);

        //验证码错误
        if (!vcSave.equals(vcode))
            return new ResponseObject(0, 3);

        //密码未设置
        if (password == null || password.equals(""))
            return new ResponseObject(0, 2);

        userService.resetPassword((String) session.getAttribute("email"), password);

        return new ResponseObject(1, 1, session.getAttribute("vcode"));
    }

    @ResponseBody
    @RequestMapping(value = "query2", method = RequestMethod.POST)
    public ResponseObject query2(@RequestParam(value = "username", required = true) String username, Model model) {
        User test;
        test = userService.querybyUserId(Integer.parseInt(username));
        return new ResponseObject(test);
    }





    /*@ResponseBody
    @RequestMapping(value = "getUserList",method = RequestMethod.POST)

    public ResponseObject getUserList(
            @RequestParam(value = "username",required = false) String username,
            @RequestParam(value = "")

    ){
    }*/

    @ResponseBody
    @RequestMapping(value = "searchUser", method = RequestMethod.GET)

    public ResponseObject searchUser(
            @RequestParam(value = "keyword", required = false, defaultValue = "") String keyword
    ) {

        if (keyword != null && !keyword.equals("")) {
            List<RecommendItem> recommendItems = userService.searchUserByKeyword(keyword);
            if (recommendItems == null || recommendItems.size() == 0)
                return new ResponseObject(0, 5);
            return new ResponseObject(1, 1, recommendItems);
        }

        return new ResponseObject(0, 0);
    }


    @ResponseBody
    @RequestMapping(value = "updateUserInfo", method = RequestMethod.POST)

    public ResponseObject updateUserInfo(
            @RequestParam(value = "name") String name,
            @RequestParam(value = "idNum") String idNum,
            @RequestParam(value = "phoneNum") String phoneNum,
            @RequestParam(value = "birthday") String birthday,
            @RequestParam(value = "domicile") String domicile,
            @RequestParam(value = "education") short education,
            @RequestParam(value = "major") String major,
            @RequestParam(value = "height") short height,
            @RequestParam(value = "weight") short weight,
            @RequestParam(value = "organizationType") short organizationType,
            @RequestParam(value = "monthlySalary") short monthlySalary,
            @RequestParam(value = "selfIntro") String selfIntro,
            @RequestParam(value = "hobby") String hobby,
            @RequestParam(value = "loveDeclaration") String loveDeclaration,
            @RequestParam(value = "favour", required = false) String favour,
            HttpSession session
    ) {
        User user = (User) session.getAttribute("user");

        if (user == null || user.getUserId() == 0)
            return new ResponseObject(0, -1);

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        Date birthdayDate;

        try {
            birthdayDate = sdf.parse(birthday);
        } catch (ParseException e) {
            e.printStackTrace();
            return new ResponseObject(0, 2);
        }

        user.setSelfIntro(selfIntro);
        user.setBirthday(birthdayDate);

        user.setPhoneNum(phoneNum);
        user.setName(name);
        user.setIdNum(idNum);

        DetailsWithBLOBs details = new DetailsWithBLOBs();

        details.setLoveDeclaration(loveDeclaration);
        details.setHobby(hobby);
        details.setWeight(weight);
        details.setHeight(height);
        details.setMonthlySalary(monthlySalary);
        details.setOrganizationType(organizationType);
        details.setEducation(education);
        details.setMajor(major);
        details.setDomicile(domicile);
        Favour newFavour = new Favour();
        if (favour != null)
            try {
                newFavour = JSONObject.parseObject(favour, Favour.class);
            } catch (Exception e) {
                return new ResponseObject(0, 2);
            }
        newFavour.setUserId(user.getUserId());
        int status = userService.updateUserInfo(user, details, newFavour);

        if (status != 1)
            return new ResponseObject(0, status);

        return new ResponseObject(1, 1);
    }

}